package xx.services;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class PageCache
{
    private Map<Integer, Page> map = new HashMap<Integer, Page>();

    private static PageCache c = new PageCache();

    private PageCache()
    {
    }

    public static final PageCache getInstance()
    {
        return c;
    }

    public boolean contains(int pageHash)
    {
        boolean b = map.containsKey(pageHash);
        if (b)
        {
            map.get(pageHash).resetTask();
        }
        return b;
    }

    public Page get(int pageHash)
    {
        return map.get(pageHash);
    }

    /**
     * 加入缓存，默认保存1小时
     * 
     * @param pageHash
     * @param value
     */
    public synchronized void push(final Page page, long cacheTime)
    {
        map.put(page.getHash(), page);

        if (cacheTime <= 0)
            cacheTime = 10;

        Timer timer = new Timer();
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
            }
        }, cacheTime * 1000);
    }

    public void remove(int hash)
    {
        map.remove(hash);
    }


    public Page instancePage(int hash, String title, String content)
    {
        return new Page(hash, title, content);
    }

    class Page
    {
        private Page(int hash, String title, String content)
        {
            this.hash = hash;
            this.title = title;
            this.content = content;
        }

        private int hash;

        private String title;

        private String content = null;

        private boolean isRead = true;

        public String getContent()
        {
            return content;
        }

        public Page setContent(String content)
        {
            this.content = content;
            return this;
        }

        public int getHash()
        {
            return hash;
        }

        public Page setHash(int hash)
        {
            this.hash = hash;
            return this;
        }

        public String getTitle()
        {
            return title;
        }

        public Page setTitle(String title)
        {
            this.title = title;
            return this;
        }

        public boolean isRead()
        {
            return isRead;
        }


        private void resetTask()
        {
            if (task != null)
                task.cancel();
            task = new TimerTask()
            {
                @Override
                public void run()
                {
                    isRead = false;
                }
            };

            timer.schedule(task, 24 * 60 * 60 * 1000);
        }

        private Timer timer = new Timer();

        private TimerTask task = null;
    }
}
